import fs from 'fs';
import path from 'path';
import markdownpdf from 'markdown-pdf';

/**
 * 生成性能测试报告的 Markdown 内容
 */
function generateMarkdownContent({
  metrics,
  failedRequests,
  slowRequests,
  imgName,
  deviceName
}) {
  const content = [];

  // 添加截图
  content.push(`## ${deviceName}页面截图\n`);
  content.push(`![页面截图](./${imgName})\n`);

  // 添加性能指标
  content.push(`## 性能指标\n`);
  content.push('| 指标 | 时间 |');
  content.push('|------|------|');
  content.push(`| 白屏时间 | ${metrics.firstPaint?.toFixed(2)}ms |`);
  content.push(`| 首屏时间 | ${metrics.firstContentfulPaint?.toFixed(2)}ms |`);
  content.push(`| DOM加载完成 | ${metrics.domContentLoaded?.toFixed(2)}ms |`);
  content.push(`| 页面完全加载 | ${metrics.loadComplete?.toFixed(2)}ms |`);
  content.push('\n');

  // 添加内存使用情况
  content.push(`## 内存使用情况\n`);
  content.push('| 指标 | 大小 |');
  content.push('|------|------|');
  content.push(
    `| 当前使用总的内存大小 | ${metrics.memoryInfo?.totalJSHeapSize}MB |`
  );
  content.push(`| 内存上限 | ${metrics.memoryInfo?.jsHeapSizeLimit}MB |`);
  content.push('\n');

  // 添加失败的资源请求
  if (failedRequests.length > 0) {
    content.push(`## 加载失败的资源\n`);
    failedRequests.forEach(req => {
      content.push(`- **URL**: ${req.url}`);
      content.push(`  - 错误: ${req.errorText}\n`);
    });
  }

  // 添加加载缓慢的资源
  if (slowRequests.length > 0) {
    content.push(`## 加载缓慢的资源 (>1s)\n`);
    slowRequests.forEach(req => {
      content.push(`- **URL**: ${req.url}`);
      content.push(`  - 加载时间: ${req.duration}ms\n`);
    });
  }

  return content.join('\n');
}

/**
 * 输出性能测试报告
 */
export async function printReport({
  metrics,
  failedRequests,
  slowRequests,
  testReportDir,
  imgName,
  deviceName = 'PC',
}) {
  // 控制台输出
  console.log('\n性能测试报告:');
  console.log('-------------------');
  console.log(`白屏时间: ${metrics.firstPaint?.toFixed(2)}ms`);
  console.log(`首屏时间: ${metrics.firstContentfulPaint?.toFixed(2)}ms`);
  console.log(`DOM加载完成: ${metrics.domContentLoaded?.toFixed(2)}ms`);
  console.log(`页面完全加载: ${metrics.loadComplete?.toFixed(2)}ms`);

  console.log('\n内存使用:');
  console.log('-------------------');
  console.log(`当前使用总的内存大小: ${metrics.memoryInfo?.totalJSHeapSize}MB`);
  console.log(`内存上限: ${metrics.memoryInfo?.jsHeapSizeLimit}MB`);

  if (failedRequests.length > 0) {
    console.log('\n加载失败的资源:');
    failedRequests.forEach(req => {
      console.log(`- ${req.url}`);
      console.log(`  错误: ${req.errorText}`);
    });
  }

  if (slowRequests.length > 0) {
    console.log('\n加载缓慢的资源 (>1s):');
    slowRequests.forEach(req => {
      console.log(`- ${req.url}`);
      console.log(`  加载时间: ${req.duration}ms`);
    });
  }

  // 生成 Markdown 文件
  const markdownContent = generateMarkdownContent({
    metrics,
    failedRequests,
    slowRequests,
    imgName,
    deviceName
  });

  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  const markdownPath = path.join(
    testReportDir,
    `performance_report_${deviceName}_${timestamp}.md`
  );
  const pdfPath = markdownPath.replace('.md', '.pdf');

  // 写入 Markdown 文件
  await fs.promises.writeFile(markdownPath, markdownContent, 'utf8');

  //   // 转换为 PDF
  //   await new Promise((resolve, reject) => {
  //     markdownpdf()
  //       .from(markdownPath)
  //       .to(pdfPath, () => {
  //         console.log(`\n报告已生成:`);
  //         console.log(`- Markdown: ${markdownPath}`);
  //         console.log(`- PDF: ${pdfPath}`);
  //         resolve();
  //       });
  //   });

  return { markdownPath, pdfPath };
}
